/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Xiaobao Zeng<zengxiaobao@skyworth.com>
 * Created Time: 2016-12-20 11:20:11
 * Last Modified: 2017-02-07 09:26:52
 * File Name: dataanalyze.go
 * Description:
 */

package statis

import (
	"encoding/json"
	//	"fmt"
	"strings"
	"time"

	"qkleague/db"
	"qkleague/errorcode"
	rpc "qkleague/rpc/client/qingke"

	//"doubimeizhi.com/datatable"
	log "github.com/cihub/seelog"
)

const (
	SORT_TYPE_WASHING_ORDER_TIMESTAMP = 1
)

type StatisInfo struct {
	All        int    `json:"all"`
	StatisName string `json:"statis_name"`
	StatisDate string `json:"statis_date"`
}

//查询用户总营收数据
func (p *QKleagueStatis) QueryAllProfit(userId string) (int, []*StatisInfo, uint) {
	sql := `select sum(total_revenue) as profits, month, userid from washingmode_day where userid = ? group by userid, month`
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userId)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, nil, errorcode.EC_GL_INTERNAL_ERROR
	}
	if len(results) == 0 {
		return 0, nil, errorcode.EC_GL_USER_HAS_NO_DATA
	}
	all := 0
	list := make([]*StatisInfo, 0)
	for _, dt := range results {
		info := &StatisInfo{}
		info.All = mysqlHelper.GetColInt(dt, "profits")
		info.StatisDate = mysqlHelper.GetColString(dt, "month")
		array := strings.Split(info.StatisDate, "-")
		info.StatisName = array[0] + "年" + array[1] + "月"

		list = append(list, info)
		all += info.All
	}
	return all, list, errorcode.EC_GL_SUCCESS
}

//查询用户特定月份的营收数据
func (p *QKleagueStatis) QuerySpecificMonthProfit(userId, month string, flag int) (int, []*StatisInfo, uint) {
	sql := `select sum(total_revenue) as profits, day, userid from washingmode_day where userid = ? and month = ? group by userid, day`

	reqMonth := ""
	if flag == 1 {
		now := time.Now().Format("2006-01-02 15:04:05")
		date := strings.Split(now, "-")
		reqMonth = date[0] + "-" + date[1]
	} else {
		reqMonth = month
	}
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userId, reqMonth)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, nil, errorcode.EC_GL_INTERNAL_ERROR
	}
	if len(results) == 0 {
		return 0, nil, errorcode.EC_GL_USER_HAS_NO_DATA
	}
	all := 0
	list := make([]*StatisInfo, 0)
	for _, dt := range results {
		info := &StatisInfo{}
		info.All = mysqlHelper.GetColInt(dt, "profits")
		info.StatisDate = mysqlHelper.GetColString(dt, "day")
		array := strings.Split(info.StatisDate, "-")
		info.StatisName = array[0] + "年" + array[1] + "月" + array[2] + "日"

		list = append(list, info)
		all += info.All
	}
	return all, list, errorcode.EC_GL_SUCCESS
}

//查询用户总订单数据
func (p *QKleagueStatis) QueryAllOrders(userId string) (int, []*StatisInfo, uint) {
	sql := `select sum(total_order) as orders, month, userid from washingmode_day where userid = ? group by userid, month`
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userId)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, nil, errorcode.EC_GL_INTERNAL_ERROR
	}
	if len(results) == 0 {
		return 0, nil, errorcode.EC_GL_USER_HAS_NO_DATA
	}
	all := 0
	list := make([]*StatisInfo, 0)
	for _, dt := range results {
		info := &StatisInfo{}
		info.All = mysqlHelper.GetColInt(dt, "orders")
		info.StatisDate = mysqlHelper.GetColString(dt, "month")
		array := strings.Split(info.StatisDate, "-")
		info.StatisName = array[0] + "年" + array[1] + "月"

		list = append(list, info)
		all += info.All
	}
	return all, list, errorcode.EC_GL_SUCCESS
}

//查询用户特定月份的订单数据
func (p *QKleagueStatis) QuerySpecificMonthOrders(userId, month string, flag int) (int, []*StatisInfo, uint) {
	sql := `select sum(total_order) as orders, day, userid from washingmode_day where userid = ? and month = ? group by userid, day`
	reqMonth := ""
	if flag == 1 {
		now := time.Now().Format("2006-01-02 15:04:05")
		date := strings.Split(now, "-")
		reqMonth = date[0] + "-" + date[1]
	} else {
		reqMonth = month
	}
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userId, reqMonth)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, nil, errorcode.EC_GL_INTERNAL_ERROR
	}
	if len(results) == 0 {
		return 0, nil, errorcode.EC_GL_USER_HAS_NO_DATA
	}
	all := 0
	list := make([]*StatisInfo, 0)
	for _, dt := range results {
		info := &StatisInfo{}
		info.All = mysqlHelper.GetColInt(dt, "orders")
		info.StatisDate = mysqlHelper.GetColString(dt, "day")
		array := strings.Split(info.StatisDate, "-")
		info.StatisName = array[0] + "年" + array[1] + "月" + array[2] + "日"

		list = append(list, info)
		all += info.All
	}
	return all, list, errorcode.EC_GL_SUCCESS
}

type WashingOrderDetail struct {
	WasherId     string `json:"washer_id"`
	OrderId      string `json:"orderid"`
	WashMode     string `json:"wash_mode"`
	PayMode      int    `json:"pay_mode"`
	PayCoin      int    `json:"pay_coin"`
	Price        int    `json:"price"`
	CreateTick   int64  `json:"create_tick"`
	CompleteTick int64  `json:"complete_tick"`
}

//查询具体的盈利或者订单信息
func (p *QKleagueStatis) QueryWashingOrderDetail(userId, day string, start, length, sortType int) (interface{}, int) {
	var resp interface{}
	if washers := rpc.QueryWasheridList(userId); washers != nil {

		b, err := json.Marshal(washers)
		if err != nil {
			log.Warnf("json err, err:%s", err.Error())
			return nil, sortType
		}
		data := make([]string, 0)
		if err = json.Unmarshal(b, &data); err != nil {
			log.Warnf("json err, err:%s", err.Error())
			return nil, sortType
		}

		switch sortType {
		case SORT_TYPE_WASHING_ORDER_TIMESTAMP:
			resp = p.sortByWashingOrderTick(data, day, start, length)
		}
		return resp, sortType
	}
	return nil, sortType
}

func (p *QKleagueStatis) sortByWashingOrderTick(washers []string, day string, start, length int) []*WashingOrderDetail {
	startStr := day + " 00:00:00"
	loc, _ := time.LoadLocation("Local") //重要：获取时区
	theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", startStr, loc)
	startTick := theTime.Unix()
	endTick := startTick + 86400

	postData := map[string]interface{}{
		"washers":    washers,
		"start_tick": startTick,
		"end_tick":   endTick,
		"start":      start,
		"length":     length,
	}
	ok, orders := rpc.GetOrdersByWasherIds(postData)
	/*sql := fmt.Sprintf(`select washer_id, orderid, wash_mode, pay_mode, pay_coin, price, order_create_tick, order_update_tick from washing_order where order_update_tick > ? and order_update_tick <= ? and order_status_code = 4 and washer_id in ('%s') order by order_update_tick desc limit ?, ?`, strings.Join(washers, `','`))
	log.Debugf("sortByWashingOrderTick, sql:%s", sql)
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	if results, err := mysqlHelper.Query(sql, startTick, endTick, start, length); err == nil {
		data := make([]*WashingOrderDetail, 0, len(results))
		for _, dt := range results {
			info := &WashingOrderDetail{}
			info.WasherId = mysqlHelper.GetColString(dt, "washer_id")
			info.OrderId = mysqlHelper.GetColString(dt, "orderid")
			info.WashMode = mysqlHelper.GetColString(dt, "wash_mode")
			info.PayMode = mysqlHelper.GetColInt(dt, "pay_mode")
			info.PayCoin = mysqlHelper.GetColInt(dt, "pay_coin")
			info.Price = mysqlHelper.GetColInt(dt, "price")
			info.CreateTick = int64(mysqlHelper.GetColInt(dt, "order_create_tick"))
			info.CompleteTick = int64(mysqlHelper.GetColInt(dt, "order_update_tick"))

			data = append(data, info)
		}
		return data
	} else {
		log.Warnf("mysql err, err:%s", err.Error())
	}*/
	//fmt.Println(orders)
	if !ok || orders == nil {
		return nil
	}
	//订单基础信息
	type OrderWashingInfo struct {
		OrderId         string  `json:"orderid"`           //订单ID
		UserId          string  `json:"userid"`            //用户ID
		PayMode         int     `json:"pay_mode"`          //支付账户类型
		PayCoin         int     `json:"pay_coin"`          //支付金额
		OrderSummary    string  `json:"order_summary"`     //订单摘要
		OrderStatus     string  `json:"order_status"`      //订单状态
		OrderStatusCode int     `json:"order_status_code"` //订单状态码
		OrderCreateTick float64 `json:"order_create_tick"`
		OrderUpdateTick float64 `json:"order_update_tick"`
		ModeId          int     `json:"mode_id"`      //模式编号
		WashModeId      int     `json:"wash_mode_id"` //洗衣模式编码
		WashMode        string  `json:"wash_mode"`    //洗衣模式
		WasherId        string  `json:"washer_id"`    //洗衣机编号
		Price           int     `json:"price"`        //原始价格
		CouponId        string  `json:"coupon_id"`    //优惠券编码
		PackOid         string  `json:"pack_oid"`     //套餐编号
	}

	req := make([]*OrderWashingInfo, 0)
	b, err := json.Marshal(orders)
	if err != nil {
		//fmt.Println(err.Error())
		log.Warnf("json err, %s", err.Error())
		return nil
	}
	if err := json.Unmarshal(b, &req); err != nil {
		//fmt.Println("unmarshal", err.Error())
		log.Warnf("json err:%s", err.Error())
		return nil
	}
	data := make([]*WashingOrderDetail, 0, len(req))
	for _, dt := range req {
		//fmt.Println("range req", dt)
		info := &WashingOrderDetail{}
		info.WasherId = dt.WasherId
		info.OrderId = dt.OrderId
		info.WashMode = dt.WashMode
		info.PayMode = dt.PayMode
		info.PayCoin = dt.PayCoin
		info.Price = dt.Price
		info.CreateTick = int64(dt.OrderCreateTick)
		info.CompleteTick = int64(dt.OrderUpdateTick)

		data = append(data, info)
	}
	return data
}
